<template>
  <el-dialog
    title="身份确认"
    :visible.sync="showDialog"
    :close-on-click-modal="false"
    width="800px"
    class="self-dialog"
    @close="close"
  >
    <p class="tip">是否确认对单证编号为 “{{rowData.preNo || rowData.platSeqNo}}” 的数据进行该操作？请按指纹或拍摄人脸照片进行确认</p>
    <div class="wrap">
      <div class="fingerBox">
        <img
          v-if="fingerprintOneStatus === null"
          src="@/assets/images/fingerprint.png"
        />
        <img
          class="img_status"
          v-if="fingerprintOneStatus === 'success'"
          src="@/assets/images/fingerprint_success.png"
        />
        <img
          class="img_status"
          v-if="fingerprintOneStatus === 'fail'"
          src="@/assets/images/fingerprint_fail.png"
        />
        <el-button
          class="finger_btn"
          type="success"
          plain
          size="mini"
          :loading="btnLoading1"
          @click="getUserFingerprint"
          >指纹确认</el-button
        >
      </div>
      <div class="fingerBox photo">
        <img
          v-if="!openCameraStatus && !showImg"
          src="@/assets/images/facePrint.png"
        />
        <div class="ui-basic-content faceBox">
          <video v-if="openCameraStatus" ref="video" autoplay class="video"></video>
          <canvas ref="canvas" style="display: none"></canvas>
          <img v-if="showImg" ref="photo" src="" class="previewImg"/>
          <div class="rightBtn">
            <!-- <el-button v-if="!openCameraStatus && !showImg" type="success" size="mini" @click="OpenCamera">打开摄像头</el-button> -->
            <el-button v-if="openCameraStatus" icon="el-icon-camera-solid" type="primary" size="mini" @click="takePhoto">拍照</el-button>
            <el-button v-if="openCameraStatus" type="danger" plain size="mini" @click="CloseCamera">关闭摄像头</el-button>
            <el-button
                v-if="!openCameraStatus && !showImg"
                class="btn"
                type="success"
                plain
                size="mini"
                @click="OpenCamera"
                >拍照确认</el-button
              >
            <div v-if="!openCameraStatus && showImg" >
              <el-button type="warning"  size="mini" @click="reCamera">重新拍摄</el-button>
              <el-button class="submitPhotoBtn" type="success" size="mini" @click="submitPhoto">确认照片</el-button>
            </div>
            
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="showDialog = false">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { contrastFaceInfo, getMacAddress, getFingerprintByIdCard } from "@/api/bt/bmhs";
import axios from "axios";
export default {
  name: "identityConfirm",
  props: {
    rowData: {
      type: Object,
      default: () => {}
    },
    idCardField: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      showDialog: false,
      btnLoading1: false,
      fingerprintOneStatus: null,
      fingerprintList: [],
      faceStatus: null,
      openCameraStatus: null,
      showImg: false,
      faceInfo: "",
      faceImgUrl: ""
    };
  },
  methods: {
    open() {
      this.showDialog = true;
    },
    close() {
      this.btnLoading1 = false,
      this.fingerprintOneStatus = null;
      this.openCameraStatus = null,
      this.showDialog = false;
    },
    // 获取用户备案的指纹
    getUserFingerprint() {
      const params = {
        idCardNo: this.rowData[this.idCardField],
      }
      getFingerprintByIdCard(params).then(res => {
        this.fingerprintList = res.data;
        this.getfingerprintMsg();
      })
    },
    // 采集指纹
    getfingerprintMsg() {
      let MacAddressStatus = sessionStorage.getItem("MacAddressStatus");
      if(MacAddressStatus) {
        this.btnLoading1 = true;
        this.fingerprintOneStatus = null;

        const templetJosn = "templet="+JSON.stringify( {
          'templet': this.fingerprintList,
        })
        axios({
          url: "http://127.0.0.1:8091/api/finger_feature?readtimeout=30000",
          method: 'post',
          headers: {
            'Content-Type':'application/x-www-form-urlencoded'
          },
          data:templetJosn,
        }).then(resstr => {
          const res = resstr.data;
          if (res.Result != 0) {
            Notification({
              title: '提示',
              message: '请确定驱动和指纹阅读器是否正常工作!',
              duration: 0
            });
          } else if (res.Data) {
            if(res.Data.Match === 'success') {
              this.btnLoading1 = false;
              this.$message({
                message: "认证成功!",
                type: "success",
              });
              let timer = setTimeout(() => {
                this.$emit("authSuccess");
                this.close();
                clearTimeout(timer);
                timer = null;
              }, 2000)
            } else {
              this.$message({
                message: "认证失败!",
                type: "error",
              });
              this.btnLoading1 = false;
            }
          }
        }).catch(() => {
          this.btnLoading1 = true;
        });
      } else {
        getMacAddress().then((res) => {
          if(res.data) {
            sessionStorage.setItem("MacAddressStatus", res.data);
            this.getfingerprintMsg();
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        })
      }
    },
    // 打开摄像头
    OpenCamera() {
      this.getCamera();
    },
    getCamera() {
      this.showImg = false;
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          this.openCameraStatus = true;
          this.$nextTick(() => {
            this.$refs.video.srcObject = stream;
          });
        })
        .catch((error) => {
          console.error("Error accessing the camera:", error);
          this.$message({
            message: "摄像头打开失败，请检查设备是否正常!",
            type: "warning",
          });
        });
    },
     // 关闭摄像头
    CloseCamera() {
      this.openCameraStatus = null;
      this.$refs.video.srcObject.getTracks()[0].stop();
    },
    reCamera() {
      this.getCamera();
      this.faceInfo = "";
      this.faceImgUrl = "";
    },
    // 人脸采集
    takePhoto() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const img = canvas.toDataURL("image/png");
      this.faceInfo = img;
      this.showImg = true;
      // 关闭摄像头
      this.CloseCamera();
      this.$nextTick(() => {
        const photo = this.$refs.photo;
        photo.src = img;
      })
    },
    submitPhoto() {
      // 对比照片
      const params = {
        idCardNo: this.rowData[this.idCardField],
        faceInfo: this.faceInfo,
      };
      contrastFaceInfo(params).then((res) => {
        if (res.data) {
          this.$message({
            message: "认证成功!",
            type: "success",
          });
          let timer = setTimeout(() => {
            this.$emit("authSuccess");
            this.close();
            clearTimeout(timer);
            timer = null;
          }, 2000)
        } else {
          this.$message({
            message: "认证失败!",
            type: "error",
          });
        }
      });

      // const file = this.base64ToBlob(this.faceInfo);
      // var formData = new FormData()
      // formData.append('file', file)
      // uploadBorderPhoto(formData).then(res => {
      //   this.faceImgUrl = res.url;
      //   this.fileName = res.fileName;
      //   const obj = {
      //     faceImgUrl: res.url,
      //     faceInfo: this.faceInfo,
      //   }
      //   this.$emit("receivePhoto", obj)
      // })
    },
  },
};
</script>

<style lang="scss" scoped>
.tip {
  text-align: center;
  color: red;
}
.wrap {
  display: flex;
  justify-content: center;
}
.fingerBox {
  width: 300px;
  min-height: 200px;
  // height: 300px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin: 10px 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  img {
    width: 75px;
    height: auto;
  }
  .img_status {
    width: 40px;
    height: auto;
  }
  .titleStatus {
    color: #000;
    font-size: 14px;
    font-weight: blod;
    margin-top: 15px;
    .success {
      color: #36ab60;
    }
    .fail {
      color: #d81e06;
    }
  }
  .tip {
    font-size: 12px;
    color: #999;
    text-align: center;
    margin-top: 15px;
  }
  .finger_btn {
    margin-top: 15px;
  }
}
.photo {
  img {
    width: 60px;
  }
}
.faceBox {
  .video {
    width: 300px;
    height: auto;
  }
  .previewImg {
    width: 300px;
    height: 225px;
  }
}
.rightBtn {
  display: flex;
  justify-content: center;
  padding: 15px 0;
}
</style>